var bgcgd_win;
var bgcgd = {
    initQuery:function () {
        //销售单位加载
        $('#bgcgd_cgdw').combotree({
            loadFilter:function (rows) {
                return convert(rows);
            },
            onSelect:function (record) {
                $('#bgcgd_cgr').combobox({
                    url:$.webPath() + '/sys/yg/ygXmList?zgjgId=' + record.id,
                    valueField:'id',
                    textField:'xm'
                });
            }
        });

        $('#bgcgd_dzck').combobox({
            url:$.webPath() + '/organ/ck/ckmcList',
            valueField:'id',
            textField:'mc',
            panelHeight:'200',
            editable:true
        });

        //客户加载
        $("[name='queryBgcgd.gys']").qyjgzcombobox();
    },
    initDatagrid:function () {
        $("#grid_bgcgd").datagrid(bgcgd.dataOptions);
    },
    initBtn:function () {
        $("#btn_bgcgd_add").click(function () {
            bgcgd.showWindow({});
        });
        $("#btn_cancel_bgcgd").click(function () {
            var row = $('#grid_bgcgd').datagrid('getSelected');
            if (row) {
                $.messager.confirm('确认', '是否取消提交此保供送货单', function (r) {
                    if (r) {
                        var index = $('#grid_bgcgd').datagrid('getRowIndex', row);
                        var newRow = row;
                        newRow["zt"] = "ybc";
                        newRow["zt_text"] = "已保存";
                        $.post($.webPath() + '/cggl/cgdgl/cgd_cancel', {"cgd.id":row.id}, function (data) {
                            var obj = eval('(' + data + ')');
                            if (obj.statusCode == '200') {
                                $('#grid_bgcgd').datagrid('updateRow', {"index":index, row:newRow});
                                bgcgd.setBtnStatus();
                                $.messager.show({title:'提示框', msg:obj.message, timeout:3000, showType:'slide'});
                            }
                            else {
                                $.messager.alert('提示', obj.message, 'info');
                            }
                        });
                    }
                });
            } else {
                $.messager.alert('提示', "请选择要取消的保供送货单", 'info');
            }
        });
        $("#btn_bgcgd_mod").click(function () {
            bgcgd.showWindow({"cgd.id":$('#grid_bgcgd').datagrid('getSelected').id});
        });
        $("#btn_bgcgd_dhyq").click(function () {
            bgcgd.showDhyqWindow({"cgd.id":$('#grid_bgcgd').datagrid('getSelected').id});
        });
        $("#btn_bgcgd_del").click(function () {
            var row = $('#grid_bgcgd').datagrid('getSelected');
            if (row) {
                $.messager.confirm('确认', '是否确认删除此保供送货单', function (r) {
                    if (r) {
                        var index = $('#grid_bgcgd').datagrid('getRowIndex', row);
                        $.post($.webPath() + '/cggl/bgcgdgl/bgcgd_del', {"cgd.id":row.id}, function (data) {
                            var obj = eval('(' + data + ')');
                            if (obj.statusCode == '200') {
//                                $('#grid_bgcgd').datagrid('deleteRow', index);
                                $('#grid_bgcgd').datagrid('reload');
                                $('#layout_bgcgd').layout('panel', 'center').panel('refresh');
                            } else {
                                $.messager.alert('提示', obj.message, 'info');
                            }
                        });
                    }
                });
            } else {
                $.messager.alert('提示', "请选择要删除的保供送货单", 'info');
            }
        });
        $("#btn_bgcgd_confirm").click(function () {
            var row = $('#grid_bgcgd').datagrid('getSelected');
            if (row) {
                $.messager.confirm('确认', '是否提交此保供送货单', function (r) {
                    if (r) {
                        var index = $('#grid_bgcgd').datagrid('getRowIndex', row);
                        var newRow = row;
                        newRow["zt"] = "ytj";
                        newRow["zt_text"] = "已提交";
                        $.post($.webPath() + '/cggl/cgdgl/cgd_confirm', {"cgd.id":row.id}, function (data) {
                            var obj = eval('(' + data + ')');
                            if (obj.statusCode == '200') {
                                $('#grid_bgcgd').datagrid('updateRow', {"index":index, row:newRow});
                                bgcgd.setBtnStatus();
                                $.messager.show({title:'提示框', msg:obj.message, timeout:3000, showType:'slide'});
                            }
                            else {
                                $.messager.alert('提示', obj.message, 'info');
                            }
                        });
                    }
                });
            } else {
                $.messager.alert('提示', "请选择要提交的送货单", 'info');
            }
        });
        //查询
        $("#btn_bgcgd_search").click(function () {
            $('#grid_bgcgd').datagrid({pageNumber:1, queryParams:bgcgd.getQuery()});
        });
    },
    setBtnStatus:function () {
        var row = $("#grid_bgcgd").datagrid("getSelected");
        if (row && row.id && row.zt == "ybc") {
            $("#btn_bgcgd_mod,#btn_bgcgd_del,#btn_bgcgd_confirm").show();
            $("#btn_bgcgd_stock").hide();
            $("#btn_cancel_bgcgd").hide();
        } else if (row && row.id && row.zt == "ytj") {
            $("#btn_bgcgd_mod,#btn_bgcgd_del,#btn_bgcgd_confirm").hide();
            $("#btn_bgcgd_stock").show();
            $("#btn_cancel_bgcgd").show();
        } else {
            $("#btn_bgcgd_mod,#btn_bgcgd_del,#btn_bgcgd_confirm,#btn_cgd_bgstock,#btn_cancel_bgcgd").hide();
        }
        if (row && row.id && row.sfgq == 'ygq') {
            $("#btn_cancel_bgcgd").hide();
            $("#btn_bgcgd_hdyq").show();
        } else {
            $("#btn_cancel_bgcgd").show();
            $("#btn_bgcgd_hdyq").hide();
        }
    },
    dataOptions:{
        url:$.webPath() + "/cggl/bgcgdgl/bgcgdList?htType=bght&sftzd=false",
        pageNumber:1,
        showFooter:true,
        onDblClickCell:function (index, field, value) {
            if (field == "cgdh") {
                $("#btn_bgcgd_mod:visible").click();
            }
        },
        loadFilter:function (data) {
            $.each(data.rows, function () {
                if (this.zt) {
                    this.zt_text = this.zt == 'ysp' ? "已审批" : this.zt == 'ybc' ? "已保存" : "已提交";
                    this.cglx_text = this.cglx == "bght" ? "保供采购" : this.cglx == "cgrk" ? "采购入库" : this.cglx == "zddh" ? "直达到货" : "统配采购";
                }
            })
            return data;
        },
        rowStyler:function (index, row) {
            if (row.zt == 'yrk') {
            }
        },
        onLoadSuccess:function () {
            $(this).datagrid('selectRow', 0);
            bgcgd.setBtnStatus();
            $(".datagrid-htable .datagrid-cell").css('text-align', 'center');
        },
        onClickRow:function () {
            bgcgd.setBtnStatus();
        },
        onSelect:function (rowIndex, rowData) {
            if (rowData) {
                bgcgd.setBtnStatus();
                if (bgcgd.selectedRowId && bgcgd.selectedRowId == rowData.id) {
                    return;
                }
                bgcgd.selectedRowId = rowData.id;
            }
        },
        columns:[
            [
                {field:'cgdh', title:'送货单号', align:'center', width:107, formatter:bgcgdCell},
                {field:'fhrq', title:'发货日期', align:'center', width:69},
                {field:'jhdhrq', title:'计划到货日期', align:'center', width:65},
                {field:'gys_qc', title:'供应商名称', align:'center', width:95},
                {field:'cglx_text', title:'采购类型', align:'center', width:51},
                {field:'cgsl', title:'采购数量', align:'right',
                    formatter:function (value) {
                        var sl = formatSlForHtml(value);
                        return sl;
                    }, width:95},
                {field:'cgje', title:'采购总金额(元)', align:'right',
                    formatter:function (value) {
                        var sl = formatJeForHtml2(value);
                        return sl;
                    }, width:113},
                {field:'glfyje', title:'物流费用(元)', align:'right',
                    formatter:function (value) {
                        var sl = formatJeForHtml2(value);
                        return sl;
                    }, width:113},
                {field:'sbgs_jc', title:'申报公司', align:'center', width:81},
                {field:'sbbm_qc', title:'申报部门', align:'center', width:92},
                {field:'sbr_xm', title:'申报人', align:'center', width:45},
                {field:'cjsj', title:'申报时间', align:'center', width:63},
                {field:'yrk', title:'入库状态', align:'center', width:54, formatter:function (value) {
                    if (value == "1")
                        return "已入库";
                    else if (value == "0")
                        return "未入库"
                }},
                {field:'zt_text', title:'状态', align:'center', width:46}
            ]
        ]
    },
    showWindow:function (cgddata) {
        if (cgddata["cgd.id"]) {
            var tit = "修改保供送货单";
            bgcgd.win_cgd = $.window({
                title:tit,
                iconCls:'icon-add2',
                width:1024,
                height:500,
                url:$.webPath() + "/cggl/bgcgdgl/bgcgdgl_content",
                data:cgddata,
                buttons:[
                    {
                        text:'保存',
                        handler:bgcgd_update
                    }
                ]
            });
        } else {
            var tit = "选择保供合同";
            var button = [
                {text:'确认', handler:function () {
                    var title = "添加保供送货单";
                    var href = $.webPath() + "/cggl/bgcgdgl/bgcgdgl_content?htType=bght&&htId=" + $("#htId").val() + "&&wzggIds=" + $("#wzggIds").val() + "&&hzmxIds=" + $("#hzmxIds").val() + "&&jhsls=" + $("#jhsls").val() + "&&htmxIds=" + $("#htmxIds").val() + "&dzckId=" + $("#ckId").val();
                    $(bgcgd.bgcgd_win).window('close');
                    bgcgd_showDialog(title, href);
                }}
            ];
            bgcgd.bgcgd_win = $.window({
                title:tit,
                iconCls:'icon-add2',
                url:$.webPath() + "/cggl/bgcgdgl/bgcgd_into",
                buttons:button,
                width:1024,
                height:500,
                model:true,
                maximizable:true,
                maximized:true,
                isMax:true
            });
        }
    },
    showDhyqWindow:function (cgddata) {
        if (cgddata["cgd.id"]) {
            var tit = "到货日期延期";
            bgcgd.win_cgd = $.window({
                title:tit,
                width:420,
                height:400,
                url:$.webPath() + "/cggl/bgcgdgl/bgcgdgl_dhyq?cgdId="+cgddata["cgd.id"],
                modal:true,
                buttons:[
                    {
                        text:'保存',
                        handler:function () {
                            bgcgd.win_cgd.mask();
                            $('#form_bgcgd_dhyq').form('submit', {
                                url:$.webPath() + "/cggl/bgcgdgl/bgcgdgl_yq",
                                onSubmit:function () {
                                    var isValid = $(this).form('validate');
                                    if (!isValid) {
                                        $(bgcgd.win_cgd).mask('hide');
                                        return false;
                                    }
                                    return isValid;
                                },
                                success:function (data) {
                                    bgcgd.win_cgd.mask('hide');
                                    var json = $.parseJSON(data);
                                    if (json.statusCode == 200) {
                                        bgcgd.win_cgd.window('close');
                                        $('#grid_bgcgd').datagrid('reload');
                                        $.messager.show({
                                            title:'提示',
                                            msg:json.message,
                                            timeout:3000,
                                            showType:'slide'
                                        });
                                    } else
                                        $.messager.alert('提示', json.message, 'error');
                                }
                            });
                        }
                    }
                ]
            });
        }
    },
    showStockWindow:function (cgddata) {
        bgcgd.win_cgd = $.window({
            title:"入库审核",
            iconCls:'icon-add',
            width:1024,
            height:500,
            url:$.webPath() + "/cggl/cgdgl/cgdgl_stock",
            data:cgddata,
            buttons:[
                {
                    text:'保存',
                    handler:cgd_stock
                }
            ]
        });
    },
    win:{},
    showDetail:function (id) {
        if ($("#layout_bgcgd #bgcgd_id").val() != id) {
            bgcgd.alwayshowDetail(id);
        }
    },
    alwayshowDetail:function (id) {
        $('#layout_bgcgd').layout('remove', 'center');
        $('#layout_bgcgd').layout('add', {
            region:'center',
            split:true,
            href:$.webPath() + '/cggl/bgcgdgl/bgcgdgl_detail?cgd.id=' + id
        });
    },
    getQuery:function () {
        return {
            "zt":$("[name='queryBgcgd.zt']").val(),
            "cglx":$("[name='queryBgcgd.cglx']").val(),
            "cgdwId":$("#bgcgd_cgdw").combotree('getValue'),
            "cgr":$("[name='queryBgcgd.cgr']").val(),
            "fhrqStart":$('#bgzdsj_start').datebox('getValue'),
            "fhrqEnd":$('#bgzdsj_end').datebox('getValue'),
            "cgdh":$("[name='queryBgcgd.cgdh']").val(),
            "wzbm":$("[name='queryBgcgd.wzbm']").val(),
            "dzckId":$('#bgcgd_dzck').combobox('getValue') == null ? null : $('#bgcgd_dzck').combotree('getValue'),
            "sfgq":$("[name='queryBgcgd.sfgq']").val(),
            "gysid":$("[name='queryBgcgd.gys']").val(),
            "rkzt":$("[name='queryBgcgd.rkzt']").val()
        }
    },
    selectedRowId:null
}

$(function () {
    //查询条件-加载
    bgcgd.initQuery();
    //按钮-加载
    bgcgd.initBtn();
    //列表-加载
    bgcgd.initDatagrid();
})


var bgcgd_win;
function bgcgd_showDialog(title, href) {

    var button = [
        {text:'保存', handler:bgcgd_add}
    ];

    bgcgd_win = $.window({
        title:title,
        iconCls:'icon-add2',
        url:href,
        width:1024,
        height:500,
        cache:false,
        buttons:button
    });
}

function bgcgd_add() {
    bgcgd_win.mask();
    $("#cgd_mx").edatagrid('saveRow');
    $("#cgd_fy").edatagrid('saveRow');
    $('#bgCgdglForm').tabs('select', "送货单");
    $("#bgCgdglForm").form('submit', {
        url:$.webPath() + "/cggl/bgcgdgl/bgcgd_add",
        onSubmit:function (param) {
            var data = $('#cgd_mx').edatagrid("getData");
            var fydata = $('#cgd_fy').edatagrid("getData");
            if (!data.rows.length) {
                bgcgd_win.mask('hide');
                $('#bgCgdglForm').tabs('select', "送货明细");
                $.messager.alert("提示", "送货明细需要填写!", "waring");
                return false;
            }
            var arrayPrefix = 'cgd.cgdmxList';
            var fyPrefix = 'cgd.cgfyList';
            //物资计划明细
            var paramString = "{";
            //物资计划明细
            for (var i = 0; i < data.rows.length; i++) {
//                if (data.rows[i]['cd.id'] == null || data.rows[i]['cd.id'] == '') {
//                    $('#bgCgdglForm').tabs('select', "采购明细");
//                    $.messager.alert('提示', '第' + (i + 1) + '行的产地不能为空 !', 'info');
//                    return false;
//                }else

//                if (data.rows[i].js == 0 || data.rows[i].js == null) {
//                    bgcgd_win.mask('hide');
//                    $('#bgCgdglForm').tabs('select', "送货明细");
//                    $.messager.alert('提示', '第' + (i + 1) + '行的件数不能为0 !', 'info');
//                    return false;
//                }
                {
                    var objectString = $.toJSONStringSubPrefix(data.rows[i], arrayPrefix + "[" + i + "].",
                        [
                            'id',
                            ['wzgg_id', 'gg.id'],
                            'cd.id',
                            'jzfs.id',
                            'hsj',
                            'bhsj',
                            'bz',
                            'sbsl',
                            'js',
                            'ph'
                        ]);
                    paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
                }
            }
            //费用物资计划
            for (var i = 0; i < fydata.rows.length; i++) {
                {
                    var objectString = $.toJSONStringPrefix(fydata.rows[i], fyPrefix + "[" + i + "].");
                    paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
                }
            }
            if (data.rows && data.rows.length > 0)
                paramString = paramString.substring(0, paramString.length - 1);
            paramString += "}";
            $.extend(param, $.parseJSON(paramString));
            var isValid = $(this).form('validate');
            if (!isValid) {
                bgcgd_win.mask('hide');
                return false;
            }
            return isValid;
        },
        success:function (data) {
            var obj = eval('(' + data + ')');
            if (obj.statusCode == '200') {
                bgcgd_win.mask('hide');
                $(bgcgd_win).window('close');
                $('#grid_bgcgd').datagrid('reload');
                $('#layout_bgcgd').layout('panel', 'center').panel('refresh');
                $.messager.show({title:'提示框', msg:obj.message, timeout:3000, showType:'slide'});
            } else {
                bgcgd_win.mask('hide');
                $.messager.alert('提示', obj.message, 'info');
            }
        }
    });
}

function bgcgd_update() {
    bgcgd.win_cgd.mask();
    $("#cgd_mx").edatagrid('saveRow');
    $("#cgd_fy").edatagrid('saveRow');
    $('#bgCgdglForm').tabs('select', "送货单");
    $("#bgCgdglForm").form('submit', {
        url:$.webPath() + "/cggl/bgcgdgl/bgcgd_uppdate",
        onSubmit:function (param) {
            var data = $('#cgd_mx').edatagrid("getData");
            var fydata = $('#cgd_fy').edatagrid("getData");
            if (!data.rows.length) {
                bgcgd.win_cgd.mask('hide');
                $('#bgCgdglForm').tabs('select', "送货明细");
                $.messager.alert("提示", "送货明细需要填写!", "waring");
                return false;
            }
            var arrayPrefix = 'cgd.cgdmxList';
            var fyPrefix = 'cgd.cgfyList';
            //物资计划明细
            var paramString = "{";
            //物资计划明细
            for (var i = 0; i < data.rows.length; i++) {
//                if (data.rows[i]['cd.id'] == null || data.rows[i]['cd.id'] == '') {
//                    $('#bgCgdglForm').tabs('select', "采购明细");
//                    $.messager.alert('提示', '第' + (i + 1) + '行的产地不能为空 !', 'info');
//                    return false;
//                }else

//                if (data.rows[i].js == 0 || data.rows[i].js == null) {
//                    $('#bgCgdglForm').tabs('select', "送货明细");
//                    $.messager.alert('提示', '第' + (i + 1) + '行的件数不能为0 !', 'info');
//                    return false;
//                }
                {
                    var objectString = $.toJSONStringSubPrefix(data.rows[i], arrayPrefix + "[" + i + "].",
                        [
                            'id',
                            ['wzgg.id', 'gg.id'],
                            'cd.id',
                            'jzfs.id',
                            'hsj',
                            'bhsj',
                            'bz',
                            'sbsl',
                            'js',
                            'ph'
                        ]);
                    paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
                }
            }
            //费用物资计划
            for (var i = 0; i < fydata.rows.length; i++) {
                {
                    var objectString = $.toJSONStringPrefix(fydata.rows[i], fyPrefix + "[" + i + "].");
                    paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
                }
            }
            if (data.rows && data.rows.length > 0)
                paramString = paramString.substring(0, paramString.length - 1);
            paramString += "}";
            $.extend(param, $.parseJSON(paramString));
            var isValid = $(this).form('validate');
            if (!isValid) {
                bgcgd.win_cgd.mask('hide');
                return false;
            }
            return isValid;
        },
        success:function (data) {
            bgcgd.win_cgd.mask('hide');
            var obj = eval('(' + data + ')');
            if (obj.statusCode == '200') {
                $(bgcgd.win_cgd).window('close');
                $('#grid_bgcgd').datagrid('reload');
                $('#layout_bgcgd').layout('panel', 'center').panel('refresh');
                $.messager.show({title:'提示框', msg:obj.message, timeout:3000, showType:'slide'});
            } else {
                $.messager.alert('提示', obj.message, 'info');
            }
        }
    });
}
